package com.liwei.lwmail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liwei.lwmail.product.service.CategoryBrandRelationService;
import com.liwei.lwmail.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.product.dao.CategoryDao;
import com.liwei.lwmail.product.entity.CategoryEntity;
import com.liwei.lwmail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    private CategoryDao categoryDao; ==>baseMapper

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子树形结构
            //找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
             categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> longs) {
        // TODO 检查当前删除的菜单是否被引用
        baseMapper.deleteBatchIds(longs);
    }

    //[2,22,255]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId,paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(cacheNames = {"category"},allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //上面的递归方法
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if(entity.getParentCid()!=0){
            findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2.菜单排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return  children;
    }

    @Cacheable(cacheNames = {"category"},key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevelOneList() {
        System.out.println("getLevelOneList方法调用了....");
        List<CategoryEntity> entityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return entityList;
    }

    //现在的缓存模式
    @Override
    @Cacheable(cacheNames = {"category"},key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1、查出所有1级分类
        List<CategoryEntity> levelOneList = getParent_cid(selectList,0L);
        //2、封装数据
        Map<String, List<Catalog2Vo>> collect = levelOneList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //3、查出此一级分类的所有二级分类
            List<CategoryEntity> list = getParent_cid(selectList,v.getCatId());
            //4、封装二级分类数据 Catalog2Vo
            List<Catalog2Vo> catalog2Vos = null;
            if (list != null) {
                catalog2Vos = list.stream().map(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(item.getCatId().toString(),
                            item.getName(), v.getCatId().toString(), null);
                    //5、查出此二级分类的所有三级分类
                    List<CategoryEntity> entityList = getParent_cid(selectList,item.getCatId());
                    //6、封装三级分类数据 Catalog3Vo
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (entityList != null){
                        catalog3Vos = entityList.stream().map(entity -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(entity.getCatId().toString(), entity.getName(), item.getCatId().toString());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    //7、三级分类Vo存入二级分类Vo
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return collect;
    }

    //TODO 堆外内存溢出
    //原来的缓存模式
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        /**
         * null结果缓存--防止穿透
         * 设置区间随机过期时间--防止雪崩
         * 加锁--防止击穿
         */
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //查询缓存
        String catalogJson = ops.get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)){
            //System.out.println("缓存未命中.......");
            //没有缓存，查询数据库
            Map<String, List<Catalog2Vo>> catalogJsonFromDatabase = getCatalogJsonFromDatabaseWithRedissonLock();
            return catalogJsonFromDatabase;
        }
        //System.out.println("缓存命中.......直接返回");
        //缓存数据转为对象
        Map<String, List<Catalog2Vo>> cacheData = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        return cacheData;
    }

    /**
     * 分布式锁
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDatabaseWithRedissonLock() {

        //1、获取分布式锁,锁的粒度越细，处理越快
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        //加锁成功,执行业务
        Map<String, List<Catalog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }

        return dataFromDB;
    }
    /**
     * 本地锁
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDatabaseWithLocalLock() {

        //TODO 本地锁问题：分布式下有问题
        synchronized (this){
            //得到锁之后，再去缓存中确认是否有缓存
            return getDataFromDB();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDB() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)){
            //缓存不为空，返回缓存数据
            Map<String, List<Catalog2Vo>> cacheData = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
            return cacheData;
        }
        //System.out.println("查询了数据库.......");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1、查出所有1级分类
        List<CategoryEntity> levelOneList = getParent_cid(selectList,0L);
        //2、封装数据
        Map<String, List<Catalog2Vo>> collect = levelOneList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //3、查出此一级分类的所有二级分类
            List<CategoryEntity> list = getParent_cid(selectList,v.getCatId());
            //4、封装二级分类数据 Catalog2Vo
            List<Catalog2Vo> catalog2Vos = null;
            if (list != null) {
                catalog2Vos = list.stream().map(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(item.getCatId().toString(),
                            item.getName(), v.getCatId().toString(), null);
                    //5、查出此二级分类的所有三级分类
                    List<CategoryEntity> entityList = getParent_cid(selectList,item.getCatId());
                    //6、封装三级分类数据 Catalog3Vo
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (entityList != null){
                        catalog3Vos = entityList.stream().map(entity -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(entity.getCatId().toString(), entity.getName(), item.getCatId().toString());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    //7、三级分类Vo存入二级分类Vo
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        //将查出对象转为json
        String jsonString = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catalogJson",jsonString,1, TimeUnit.DAYS);
        return collect;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

}